
package com.kugou.game.sdk.adapter;

import com.kugou.game.sdk.base.BaseListAdapter;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.entity.GiftBag;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.Html;
import android.text.Layout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:礼包领取列表适配器
 * 
 * @author liux
 * @since 2014-8-16 下午03:22:37
 */
public class GiftBagCollectAdapter extends BaseListAdapter<GiftBag> implements OnClickListener {

    public GiftBagCollectAdapter(Context context, ViewGroup viewGroup) {
        super(context, viewGroup);
    }

    @Override
    public GiftBag getItem(int position) {
        if (mDatas != null && position >= 0 && position < mDatas.size()) {
            return mDatas.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return mDatas.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder cache;
        if (convertView == null) {
            convertView = mInflater.inflate(Rx.layout.kg_giftbag_list_item, null);
            cache = new ViewHolder();
            cache.btn_get_giftbag = (Button) convertView.findViewById(Rx.id.kg_btn_get_giftbag);
            cache.tv_giftbag_content = (TextView) convertView
                    .findViewById(Rx.id.kg_tv_giftbag_content);
            cache.tv_giftbag_name = (TextView) convertView.findViewById(Rx.id.kg_tv_giftbag_name);
            cache.tv_giftbag_progress = (TextView) convertView
                    .findViewById(Rx.id.kg_tv_giftbag_progress);
            cache.iv_giftbag_icon = (ImageView) convertView.findViewById(Rx.id.kg_iv_giftbag_icon);
            cache.pb_giftbag = (ProgressBar) convertView.findViewById(Rx.id.kg_pb_giftbag_num);
            cache.layout_gift_content = (LinearLayout) convertView
                    .findViewById(Rx.id.kg_layout_progeress_info);
            cache.btn_open_close = (ImageView) convertView.findViewById(Rx.id.kg_ib_open_close);
            cache.tv_serianum = (TextView) convertView.findViewById(Rx.id.kg_tv_giftbag_number);
            cache.tv_giftbag_tips = (TextView) convertView.findViewById(Rx.id.kg_tv_giftbag_tips);
            convertView.setTag(Rx.id.kg_giftbaglist_item_tag, cache);
        } else {
            cache = (ViewHolder) convertView.getTag(Rx.id.kg_giftbaglist_item_tag);
        }
        GiftBag giftbag = getItem(position);
        String iconUrl = giftbag.getIconUrl();
        String imgKey = iconUrl + "-" + position;
        String savePath = FolderManager.IMAGE_CACHE_FOLDER + AppUtil.getFileNameFromUrl(iconUrl);
        cache.iv_giftbag_icon.setTag(imgKey);
        Bitmap bitmap = mAsyncImageLoader.loadImage(mContext, imgKey, iconUrl, savePath, this);
        if (bitmap == null) {
            cache.iv_giftbag_icon.setImageResource(Rx.drawable.kg_app_icon_default);
        } else {
            cache.iv_giftbag_icon.setImageBitmap(bitmap);
            setFadeIn(cache.iv_giftbag_icon);
        }

        cache.btn_get_giftbag.setOnClickListener(this);
        cache.btn_open_close.setOnClickListener(this);
        cache.tv_giftbag_content.setOnClickListener(this);
        processData(cache, giftbag);
        return convertView;
    }

    private static void setInVisiable(ViewHolder cache) {
        cache.pb_giftbag.setVisibility(View.GONE);
        cache.tv_giftbag_tips.setVisibility(View.GONE);
        cache.tv_serianum.setVisibility(View.GONE);
        cache.btn_get_giftbag.setEnabled(false);
        cache.tv_giftbag_progress.setVisibility(View.GONE);
    }

    @SuppressWarnings("deprecation")
    private void processData(ViewHolder cache, GiftBag giftbag) {
        cache.tv_giftbag_progress.setText(getProgrss(giftbag.getLeftNumber(),
                giftbag.getTotalNumber()));
        cache.tv_giftbag_content.setText(stringFilter(giftbag.getGiftContent()));
        cache.tv_giftbag_name.setText(giftbag.getGiftName());
        cache.btn_get_giftbag.setTag(giftbag);
        cache.btn_get_giftbag.setClickable(true);
        cache.tv_serianum.setText(Html.fromHtml("<font color=#ff666666>已领取：</font>"
                + "<font color=#fc5f28>" + giftbag.getExistscardnumber() + "</font>"));
        ViewTreeObserver viewTreeObserver = cache.tv_giftbag_content.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new tvPreDrawListener(cache.tv_giftbag_content,
                cache.btn_open_close, giftbag));

        setInVisiable(cache);
        if (giftbag.getExtstatus() == 2) {
            cache.btn_get_giftbag.setText("淘号");
            cache.btn_get_giftbag.setBackgroundResource(Rx.drawable.kg_selector_btn_blue);
            cache.btn_get_giftbag.setEnabled(true);
            cache.pb_giftbag.setVisibility(View.VISIBLE);
            cache.tv_giftbag_progress.setVisibility(View.VISIBLE);
            cache.tv_giftbag_progress.setText("剩余0%");
            cache.pb_giftbag.setMax(100);
            cache.pb_giftbag.setProgress(0);
        } else if (!TextUtils.isEmpty(giftbag.getExistscardnumber())) {
            cache.btn_get_giftbag.setEnabled(true);
            cache.tv_giftbag_tips.setVisibility(View.VISIBLE);
            cache.tv_serianum.setVisibility(View.VISIBLE);
            cache.btn_get_giftbag.setText("复制");
            cache.btn_get_giftbag.setBackgroundResource(Rx.drawable.kg_selector_btn_blue);
        } else if (giftbag.getExtstatus() == 0) {
            cache.btn_get_giftbag.setText("领取");
            cache.btn_get_giftbag.setBackgroundResource(Rx.drawable.kg_selector_btn_blue);
            cache.btn_get_giftbag.setEnabled(true);
            cache.pb_giftbag.setVisibility(View.VISIBLE);
            cache.tv_giftbag_progress.setVisibility(View.VISIBLE);
            cache.pb_giftbag.setMax(giftbag.getTotalNumber());
            cache.pb_giftbag.setProgress(giftbag.getLeftNumber());
        } else if (giftbag.getExtstatus() == 1) {
            cache.btn_get_giftbag.setText("已领完");
            cache.btn_get_giftbag.setBackgroundResource(Rx.drawable.kg_selector_btn_gray);
            cache.pb_giftbag.setVisibility(View.VISIBLE);
            cache.tv_giftbag_progress.setVisibility(View.VISIBLE);
            cache.pb_giftbag.setMax(100);
            cache.pb_giftbag.setProgress(0);
        } else if (giftbag.getExtstatus() == 3) {
            cache.btn_get_giftbag.setText("已过期");
            cache.btn_get_giftbag.setBackgroundResource(Rx.drawable.kg_selector_btn_gray);
            cache.btn_get_giftbag.setEnabled(false);
            cache.pb_giftbag.setVisibility(View.VISIBLE);
            cache.tv_giftbag_progress.setVisibility(View.VISIBLE);
            cache.pb_giftbag.setMax(100);
            cache.pb_giftbag.setProgress(0);
        }
    }

    private static String getProgrss(int num, int total) {
        StringBuilder sb = new StringBuilder("剩余");
        if (total > 0 && num >= 0) {
            sb.append((int) num * 100 / total);
        } else {
            sb.append(0);
        }
        sb.append("%");
        return sb.toString();
    }

    @Override
    public void onClick(View v) {
        if (!NetWorkUtil.isNetworkAvailable(mContext)) {
            ToastUtil.showMsg("当前网络状态不可用，请检查网络...");
            return;
        }
        if (v.getId() == Rx.id.kg_btn_get_giftbag) {
            if (mListener != null) {
                GiftBag info = (GiftBag) v.getTag();
                mListener.onGiftBtnClickListener(v, info);
            }
        } else {
            performOnClickListener(v);
        }
    }

    public void performOnClickListener(View view) {
        if (view.getId() == Rx.id.kg_tv_giftbag_content || view.getId() == Rx.id.kg_ib_open_close) {
            TextView tvGiftContet = (TextView) ((View) view.getParent())
                    .findViewById(Rx.id.kg_tv_giftbag_content);
            ImageView ibOpenClose = (ImageView) ((View) view.getParent())
                    .findViewById(Rx.id.kg_ib_open_close);
            if (tvGiftContet.getEllipsize() == TruncateAt.END) {
                tvGiftContet.setEllipsize(null);
                tvGiftContet.setMaxLines(Integer.MAX_VALUE);
                if (ibOpenClose.getVisibility() == View.VISIBLE) {
                    ibOpenClose.setSelected(true);
                    ibOpenClose.setImageResource(Rx.drawable.kg_arrow_up);
                }
            } else {
                tvGiftContet.setMaxLines(2);
                tvGiftContet.setEllipsize(TruncateAt.END);
                if (ibOpenClose.getVisibility() == View.VISIBLE) {
                    ibOpenClose.setSelected(false);
                    ibOpenClose.setImageResource(Rx.drawable.kg_arrow_down);
                }
            }
        }
    }

    public static String stringFilter(String str) {
        if (str == null) {
            return "";
        }
        str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("！", "!")
                .replaceAll("：", ":");// 替换中文标号
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static class ViewHolder {
        /**
         * 礼包图标
         */
        public ImageView iv_giftbag_icon;

        /**
         * 礼包名称
         */
        public TextView tv_giftbag_name;

        /**
         * 进度条显示
         */
        public ProgressBar pb_giftbag;

        /**
         * 进度条的数字显示
         */
        public TextView tv_giftbag_progress;

        /**
         * 礼包串码
         */
        public TextView tv_serianum;

        /**
         * 领取,复制，已领完
         */
        public Button btn_get_giftbag;

        /**
         * 礼包描述
         */
        public TextView tv_giftbag_content;

        /**
         * 复制栏
         */
        public ImageView btn_open_close;

        /** 礼包详情布局 */
        public View layout_gift_content;

        /**
         * 领取礼包的提示，文字内容，领取8小时后进入淘号库,请尽快激活
         */
        public TextView tv_giftbag_tips;
    }

    private GiftBtnClickListener mListener;

    public void setGiftBtnClickListener(GiftBtnClickListener listener) {
        mListener = listener;
    }

    public interface GiftBtnClickListener {
        void onGiftBtnClickListener(View v, GiftBag info);

    }

    private static class tvPreDrawListener implements OnPreDrawListener {
        private boolean hasGetLines;

        private TextView mTextView;

        private View mButton;

        private GiftBag giftbag;

        public tvPreDrawListener(TextView mTextView, View mButton, GiftBag giftBag) {
            this.mTextView = mTextView;
            this.mButton = mButton;
            this.giftbag = giftBag;
            mButton.setEnabled(true);
            mTextView.setEnabled(true);
            mTextView.setEllipsize(TruncateAt.END);
        }

        @Override
        public boolean onPreDraw() {
            // 只需要获取一次就可以了
            if (!hasGetLines) {
                // 这里获取到完全展示的maxLine
                int maxLines = mTextView.getLineCount();
                // 设置maxLine的默认值，这样用户看到View就是限制了maxLine的TextView
                hasGetLines = true;
                if (maxLines > 2) {
                    mTextView.setLines(2);
                    mButton.setVisibility(View.VISIBLE);
                } else {
                    // 有些机型读取行数会直接失败，所以要添加这种方式，这种 计算TextView的长度
                    // 的方式对于\r\n计算不准确
                    TextPaint pFont = mTextView.getPaint();
                    String tvStr = giftbag.getGiftContent();
                    int strwid = (int) Layout.getDesiredWidth(tvStr, 0, tvStr.length(), pFont);
                    int padding = AppUtil.dip2px(mTextView.getContext(), mTextView.getPaddingLeft()
                            + mTextView.getPaddingRight());
                    int displayW = mTextView.getWidth();
                    int lines = 1;
                    try {
                        lines = strwid / (displayW - padding)
                                + (strwid % (displayW - padding) == 0 ? 0 : 1);
                    } catch (Exception e) {
                    }
                    if (lines > 2) {
                        mTextView.setLines(2);
                        mButton.setVisibility(View.VISIBLE);
                    } else {
                        mButton.setVisibility(View.INVISIBLE);
                        mButton.setEnabled(false);
                        mTextView.setEnabled(false);
                    }
                }
            }
            return true;
        }

    }
}
